package com.yeskery.nut.util;

import com.yeskery.nut.core.*;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.stream.Stream;

/**
 * 资源工具类
 * @author YESKERY
 * 2024/8/13
 */
public class ResourceUtils {

    /** 类路径前缀 */
    private static final String CLASSPATH_URL_PREFIX = "classpath:";

    /** 文件前缀 */
    private static final String FILE_URL_PREFIX = "file:";

    /** url前缀 */
    private static final String URL_PREFIX = "url:";

    /**
     * 是否支持该资源
     * @param value 参数值
     * @return 是否支持该资源
     */
    public static boolean isSupport(String value) {
        if (value.startsWith(CLASSPATH_URL_PREFIX)) {
            return true;
        } else if (value.startsWith(FILE_URL_PREFIX)) {
            return true;
        } else if (value.startsWith(URL_PREFIX)) {
            return true;
        }
        return Stream.of(CLASSPATH_URL_PREFIX, FILE_URL_PREFIX, URL_PREFIX).anyMatch(value::startsWith);
    }

    /**
     * 获取资源对象
     * @param value 参数值
     * @return 资源对象
     */
    public static InputStreamResource getInputStreamResource(String value) {
        if (StringUtils.isEmpty(value)) {
            throw new NutException("Resource Value Must Not Be Empty.");
        }
        if (value.startsWith(CLASSPATH_URL_PREFIX)) {
            return new ClassPathResource(value.substring(CLASSPATH_URL_PREFIX.length()));
        } else if (value.startsWith(FILE_URL_PREFIX)) {
            return new FileResourceImpl(new java.io.File(value.substring(FILE_URL_PREFIX.length())));
        } else if (value.startsWith(URL_PREFIX)) {
            return new UrlResource(value.substring(URL_PREFIX.length()));
        }
        throw new NutException("UnSupport Resource Prefix For Value[" + value + "].");
    }

    /**
     * 创建资源对象
     * @param type 类型
     * @param bytes 字节数组
     * @return 资源对象
     */
    public static InputStreamResource createInputStreamResourceObject(Class<?> type, byte[] bytes) {
        if (InputStreamResource.class.equals(type)) {
            return () -> new ByteArrayInputStream(bytes);
        } else if (Resource.class.equals(type)) {
            return new Resource() {
                @Override
                public String getName() {
                    return "";
                }

                @Override
                public Long length() {
                    return (long) bytes.length;
                }

                @Override
                public InputStream getInputStream() {
                    return new ByteArrayInputStream(bytes);
                }
            };
        }
        throw new IllegalArgumentException("UnSupport Resource Type For Type[" + type.getName() + "].");
    }
}
